package mySeleniumDriver;

import java.io.File;

import com.mercury.qualitycenter.otaclient.ClassFactory;
import com.mercury.qualitycenter.otaclient.IAttachment;
import com.mercury.qualitycenter.otaclient.IAttachmentFactory;
import com.mercury.qualitycenter.otaclient.IBaseFactory;
import com.mercury.qualitycenter.otaclient.IExtendedStorage;
import com.mercury.qualitycenter.otaclient.IList;
import com.mercury.qualitycenter.otaclient.IRun;
import com.mercury.qualitycenter.otaclient.IRunFactory;
import com.mercury.qualitycenter.otaclient.ITSTest;
import com.mercury.qualitycenter.otaclient.ITestSet;
import com.mercury.qualitycenter.otaclient.ITestSetFactory;
import com.mercury.qualitycenter.otaclient.ITestSetFolder;
import com.mercury.qualitycenter.otaclient.ITestSetTreeManager;
import com4j.Com4jObject;

public class QualityCenter extends BaseClass {

  public void connectToQC() {
    try {
      // Connect to QC
      log("info", "Trying to Connect to Quality Center....");
      String QCAuthDetails[] = gs_QCAuth.split(":");
      itdc = ClassFactory.createTDConnection();
      itdc.initConnectionEx(gs_QCUrl);
      itdc.connectProjectEx(QCAuthDetails[0], QCAuthDetails[1], QCAuthDetails[2], QCAuthDetails[3]);
      log("info", "Connected to Quality Center Successfully.");

      String testSetDetailPath[] = gs_QCTestSet.replace('/', '\\').split("\\\\");
      String strTestSetName = testSetDetailPath[testSetDetailPath.length - 1];
      String strTestLabPath =
          gs_QCTestSet.substring(0, gs_QCTestSet.length() - (strTestSetName.length() + 1)).replace(
              '/', '\\');


      // Check if test set path is available in test lab of QC.
      log("info", "Checking for test set path[] in Test lab of Quality Center....");

      (itdc.testSetFactory()).queryInterface(ITestSetFactory.class);
      ITestSetTreeManager objTestSetTreeManager =
          (itdc.testSetTreeManager()).queryInterface(ITestSetTreeManager.class);
      ITestSetFolder objTestSetFolder =
          (objTestSetTreeManager.nodeByPath(strTestLabPath)).queryInterface(ITestSetFolder.class);

      log("info", "Test set path found in Test lab Quality Center....");

      // Check if test set name is available in the path
      log("info", "Checking for Test set name{" + strTestSetName
          + "} in the set path in Quality Center....");
      IList its1 = objTestSetFolder.findTestSets(null, true, null);
      existTest = false;
      testSet = null;
      for (int i = 1; i <= its1.count(); i++) {
        Com4jObject comObj = (Com4jObject) its1.item(i);
        ITestSet tst = comObj.queryInterface(ITestSet.class);

        if (strTestSetName.equalsIgnoreCase(tst.name())) {
          testSet = tst;
          existTest = true;
          break;
        }
      }
      if (existTest) {
        log("info", "Test set found in Quality Center....");

        // Get all the test case names from the test set
        log("info", "Trying to retrieve the test case names from the test set[]");

        IBaseFactory obj2 = testSet.tsTestFactory().queryInterface(IBaseFactory.class);
        tstestlist = obj2.newList("");

        log("info", "Total Test cases in the Test set = " + tstestlist.count());

      } else {
        log("error", "Test set NOT found in Quality Center....");
      }

    } catch (Exception e) {
      log("error", "Exception while trying to connect to QC- " + e.getMessage());
    }
  }



  public void updateTestResultInQC(String strTestCasename, String executionStatus) {

    try {

      if (itdc == null) {
        log("error", "Not Connected to Quality center.Test Execution status won't be updated in QC");
      }

      else if (existTest != true) {
        log("error",
            "Test Execution status won't be updated in Quality Center coz Test set is not present.");
      } else {

        log("info", "Checking for the test case in the test set in quality center....");
        boolean testcaseExist = false;
        ITSTest testCase = null;
        for (Com4jObject obj3 : tstestlist) {
          ITSTest tstest = obj3.queryInterface(ITSTest.class);
          if (strTestCasename.substring(0, strTestCasename.length() - 4).equalsIgnoreCase(
              tstest.testName())) {
            testcaseExist = true;
            testCase = tstest;
            break;
          }
        }


        if (testcaseExist) {
          log("info", "Test case found in the test set in quality center.");
          log("info", " Current status of the test case is : " + testCase.status());

          log("info", "Running a new Test instance... ");
          IRunFactory runfactory = testCase.runFactory().queryInterface(IRunFactory.class);
          IRun run = runfactory.addItem("RunNew").queryInterface(IRun.class);
          run.status(executionStatus);
          run.post();

          log("info", "Updated status of the test case to : " + executionStatus);

        } else {
          log("error", "Test case NOT found in the test set in quality center.");
        }

      }

    } catch (Exception e) {
      log("error", "Exception caught in updateTestResultInQC function: " + e.getMessage());
    }
  }

  public void uploadTestResultZipToQC(String zipFileName) {

    try {
      String fileName = new File(zipFileName).getName();
      String folderName = new File(zipFileName).getParent();

      log("info", "Trying to attach the file: " + fileName + " from dir " + folderName
          + " to the Test set in QC...");

      IAttachmentFactory attachfac = testSet.attachments().queryInterface(IAttachmentFactory.class);
      IAttachment attach = attachfac.addItem(fileName).queryInterface(IAttachment.class);
      IExtendedStorage extAttach =
          attach.attachmentStorage().queryInterface(IExtendedStorage.class);
      extAttach.clientPath(folderName);
      extAttach.save(fileName, true);
      attach.description("The Test Results zip file is attached automatically from Selenium Test");
      attach.post();
      attach.refresh();

      log("info", "zip file is attached to the Test set Successfully!");

    } catch (Exception e) {
      log("error", "Exception caught in uploadTestResultZipToQC function: " + e.getMessage());
    }
  }


  public void disconnectFromQC() {
    itdc.disconnectProject();
    itdc.releaseConnection();
    log("info", "Logged out of Quality Center Successfully.");
  }


}
